"""
管理员监控界面 - 现代化版本
"""
import tkinter as tk
from tkinter import ttk
from .styles import COLORS, FONTS, SPACING, create_card_frame


class MonitorPanel:
    """管理员监控面板"""
    
    def __init__(self, central_ac):
        self.central_ac = central_ac
        
        self.window = tk.Toplevel()
        self.window.title("空调监控系统")
        self.window.geometry("1200x800")
        self.window.resizable(True, True)  # 允许调整大小
        self.window.minsize(1000, 700)  # 设置最小尺寸
        self.window.configure(bg=COLORS['background'])
        
        # 添加全屏支持（F11切换）
        self.is_fullscreen = False
        self.window.bind('<F11>', self._toggle_fullscreen)
        self.window.bind('<Escape>', self._exit_fullscreen)
        
        self._setup_ui()
        self._configure_styles()
        self._update_display()
        
        # 定期更新
        self.window.after(1000, self._auto_update)
    
    def _configure_styles(self):
        """配置ttk样式"""
        style = ttk.Style()
        
        # 配置Notebook样式
        style.configure(
            'Modern.TNotebook',
            background=COLORS['background'],
            borderwidth=0
        )
        style.configure(
            'Modern.TNotebook.Tab',
            padding=[SPACING['lg'], SPACING['md']],
            font=FONTS['body_bold'],
            background=COLORS['surface']
        )
        style.map(
            'Modern.TNotebook.Tab',
            background=[('selected', COLORS['primary'])],
            foreground=[('selected', '#FFFFFF'), ('!selected', COLORS['text_primary'])]
        )
        
        # 配置Treeview样式
        style.configure(
            'Modern.Treeview',
            background=COLORS['surface'],
            foreground=COLORS['text_primary'],
            fieldbackground=COLORS['surface'],
            borderwidth=0,
            font=FONTS['body'],
            rowheight=35
        )
        style.configure(
            'Modern.Treeview.Heading',
            background=COLORS['primary'],
            foreground='white',
            borderwidth=0,
            font=FONTS['body_bold'],
            relief=tk.FLAT
        )
        style.map(
            'Modern.Treeview',
            background=[('selected', COLORS['primary_light'])],
            foreground=[('selected', 'white')]
        )
    
    def _setup_ui(self):
        """设置UI界面"""
        # 标题栏
        header_frame = tk.Frame(
            self.window,
            bg=COLORS['primary'],
            height=90
        )
        header_frame.pack(fill=tk.X)
        header_frame.pack_propagate(False)
        
        title_label = tk.Label(
            header_frame,
            text="空调监控系统",
            font=FONTS['title'],
            bg=COLORS['primary'],
            fg='white'
        )
        title_label.pack(pady=(SPACING['lg'], SPACING['xs']))
        
        subtitle_label = tk.Label(
            header_frame,
            text="实时监控 · 服务管理 · 状态跟踪",
            font=FONTS['body'],
            bg=COLORS['primary'],
            fg='#E0E7FF'
        )
        subtitle_label.pack()
        
        # 主内容区
        content_frame = tk.Frame(
            self.window,
            bg=COLORS['background'],
            padx=SPACING['lg'],
            pady=SPACING['lg']
        )
        content_frame.pack(fill=tk.BOTH, expand=True)
        
        # 统计概览卡片
        self._create_overview_section(content_frame)
        
        # 创建笔记本（标签页）
        notebook = ttk.Notebook(content_frame, style='Modern.TNotebook')
        notebook.pack(fill=tk.BOTH, expand=True, pady=(SPACING['lg'], 0))
        
        # 服务队列标签页
        service_frame = tk.Frame(notebook, bg=COLORS['background'])
        notebook.add(service_frame, text="服务队列")
        self._setup_service_tab(service_frame)
        
        # 等待队列标签页
        waiting_frame = tk.Frame(notebook, bg=COLORS['background'])
        notebook.add(waiting_frame, text="等待队列")
        self._setup_waiting_tab(waiting_frame)
        
        # 房间状态标签页
        rooms_frame = tk.Frame(notebook, bg=COLORS['background'])
        notebook.add(rooms_frame, text="房间状态")
        self._setup_rooms_tab(rooms_frame)
    
    def _create_overview_section(self, parent):
        """创建统计概览区域"""
        overview_frame = tk.Frame(parent, bg=COLORS['background'])
        overview_frame.pack(fill=tk.X, pady=(0, SPACING['md']))
        
        # 创建4个统计卡片
        self.stats_cards = []
        
        stats_data = [
            ("服务中", "0", COLORS['secondary']),
            ("等待中", "0", COLORS['warning']),
            ("在线房间", "0", COLORS['info']),
            ("总房间数", "10", COLORS['text_secondary'])
        ]
        
        for i, (title, value, color) in enumerate(stats_data):
            shadow_frame, card = create_card_frame(overview_frame)
            card.config(padx=SPACING['lg'], pady=SPACING['md'])
            
            # 标题
            tk.Label(
                card,
                text=title,
                font=FONTS['small'],
                fg=COLORS['text_secondary'],
                bg=COLORS['card_bg']
            ).pack(anchor=tk.W)
            
            # 数值
            value_label = tk.Label(
                card,
                text=value,
                font=('Segoe UI', 28, 'bold'),
                fg=color,
                bg=COLORS['card_bg']
            )
            value_label.pack(anchor=tk.W, pady=(SPACING['xs'], 0))
            
            self.stats_cards.append((shadow_frame, value_label))
            
            # 计算列的宽度和间距
            if i < len(stats_data):
                padx = (0, SPACING['md']) if i < len(stats_data) - 1 else (0, 0)
                shadow_frame.pack(side=tk.LEFT, expand=True, fill=tk.BOTH, padx=padx)
    
    def _setup_service_tab(self, parent):
        """设置服务队列标签页"""
        # 卡片容器
        shadow_frame, card = create_card_frame(parent)
        shadow_frame.pack(fill=tk.BOTH, expand=True, padx=SPACING['md'], pady=SPACING['md'])
        
        # 创建表格
        columns = ('房间号', '服务对象ID', '风速', '服务时长(秒)')
        self.service_tree = ttk.Treeview(
            card,
            columns=columns,
            show='headings',
            height=15,
            style='Modern.Treeview'
        )
        
        # 设置列标题
        column_widths = {'房间号': 150, '服务对象ID': 150, '风速': 150, '服务时长(秒)': 150}
        for col in columns:
            self.service_tree.heading(col, text=col)
            self.service_tree.column(col, width=column_widths.get(col, 150), anchor=tk.CENTER)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(card, orient=tk.VERTICAL, command=self.service_tree.yview)
        self.service_tree.configure(yscroll=scrollbar.set)
        
        self.service_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=SPACING['md'], pady=SPACING['md'])
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y, pady=SPACING['md'], padx=(0, SPACING['md']))
    
    def _setup_waiting_tab(self, parent):
        """设置等待队列标签页"""
        # 卡片容器
        shadow_frame, card = create_card_frame(parent)
        shadow_frame.pack(fill=tk.BOTH, expand=True, padx=SPACING['md'], pady=SPACING['md'])
        
        # 创建表格
        columns = ('房间号', '风速', '已等待(秒)', '分配等待(秒)', '优先级提升')
        self.waiting_tree = ttk.Treeview(
            card,
            columns=columns,
            show='headings',
            height=15,
            style='Modern.Treeview'
        )
        
        # 设置列标题
        column_widths = {'房间号': 120, '风速': 120, '已等待(秒)': 150, '分配等待(秒)': 150, '优先级提升': 120}
        for col in columns:
            self.waiting_tree.heading(col, text=col)
            self.waiting_tree.column(col, width=column_widths.get(col, 120), anchor=tk.CENTER)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(card, orient=tk.VERTICAL, command=self.waiting_tree.yview)
        self.waiting_tree.configure(yscroll=scrollbar.set)
        
        self.waiting_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=SPACING['md'], pady=SPACING['md'])
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y, pady=SPACING['md'], padx=(0, SPACING['md']))
    
    def _setup_rooms_tab(self, parent):
        """设置房间状态标签页"""
        # 卡片容器
        shadow_frame, card = create_card_frame(parent)
        shadow_frame.pack(fill=tk.BOTH, expand=True, padx=SPACING['md'], pady=SPACING['md'])
        
        # 创建表格
        columns = ('房间号', '当前温度', '目标温度', '风速', '模式', '状态', '费用(元)')
        self.rooms_tree = ttk.Treeview(
            card,
            columns=columns,
            show='headings',
            height=15,
            style='Modern.Treeview'
        )
        
        # 设置列标题
        column_widths = {
            '房间号': 100,
            '当前温度': 120,
            '目标温度': 120,
            '风速': 100,
            '模式': 100,
            '状态': 120,
            '费用(元)': 120
        }
        for col in columns:
            self.rooms_tree.heading(col, text=col)
            self.rooms_tree.column(col, width=column_widths.get(col, 100), anchor=tk.CENTER)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(card, orient=tk.VERTICAL, command=self.rooms_tree.yview)
        self.rooms_tree.configure(yscroll=scrollbar.set)
        
        self.rooms_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=SPACING['md'], pady=SPACING['md'])
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y, pady=SPACING['md'], padx=(0, SPACING['md']))
    
    def _update_display(self):
        """更新显示"""
        info = self.central_ac.get_monitoring_info()
        
        # 更新统计卡片
        self.stats_cards[0][1].config(text=str(len(info['service_queue'])))  # 服务中
        self.stats_cards[1][1].config(text=str(len(info['waiting_queue'])))  # 等待中
        
        # 计算在线房间数
        online_rooms = sum(1 for room in info['room_states'] if room['is_on'])
        self.stats_cards[2][1].config(text=str(online_rooms))  # 在线房间
        
        # 更新服务队列
        self.service_tree.delete(*self.service_tree.get_children())
        for service in info['service_queue']:
            # 风速文本（简洁显示）
            wind_map = {'high': '高风', 'medium': '中风', 'low': '低风'}
            wind_text = wind_map.get(service['wind_speed'], service['wind_speed'])
            
            self.service_tree.insert('', tk.END, values=(
                service['room_id'],
                service['service_object_id'],
                wind_text,
                f"{service['service_duration']:.1f}"
            ))
        
        # 更新等待队列
        self.waiting_tree.delete(*self.waiting_tree.get_children())
        for waiting in info['waiting_queue']:
            # 风速文本（简洁显示）
            wind_map = {'high': '高风', 'medium': '中风', 'low': '低风'}
            wind_text = wind_map.get(waiting['wind_speed'], waiting['wind_speed'])
            priority_text = '是' if waiting['priority_boosted'] else '否'
            
            self.waiting_tree.insert('', tk.END, values=(
                waiting['room_id'],
                wind_text,
                f"{waiting['waiting_duration']:.1f}",
                waiting['allocated_wait_time'],
                priority_text
            ))
        
        # 更新房间状态
        self.rooms_tree.delete(*self.rooms_tree.get_children())
        for room in info['room_states']:
            # 确定状态
            if room['is_on']:
                if room['is_serving']:
                    status = '服务中'
                elif room['is_waiting']:
                    status = '等待中'
                else:
                    status = '待机中'
            else:
                status = '关闭'
            
            # 风速文本（简洁显示）
            wind_map = {'high': '高风', 'medium': '中风', 'low': '低风'}
            wind_text = wind_map.get(room['wind_speed'], '--') if room['wind_speed'] else '--'
            
            # 模式文本（简洁显示）
            mode_text = '制冷' if room['mode'] == 'cooling' else '制热'
            
            self.rooms_tree.insert('', tk.END, values=(
                room['room_id'],
                f"{room['current_temp']:.1f}°C" if room['current_temp'] else '--',
                f"{room['target_temp']:.1f}°C" if room['target_temp'] else '--',
                wind_text,
                mode_text,
                status,
                f"¥{room['total_cost']:.2f}"
            ))
    
    def _auto_update(self):
        """自动更新"""
        if self.window.winfo_exists():
            self._update_display()
            self.window.after(1000, self._auto_update)
    
    def _toggle_fullscreen(self, event=None):
        """切换全屏模式"""
        self.is_fullscreen = not self.is_fullscreen
        self.window.attributes('-fullscreen', self.is_fullscreen)
    
    def _exit_fullscreen(self, event=None):
        """退出全屏"""
        self.is_fullscreen = False
        self.window.attributes('-fullscreen', False)
    
    def show(self):
        """显示窗口"""
        self.window.mainloop()
